"use client"
import React, { useCallback } from "react"
import {
  ReactFlow,
  addEdge,
  Background,
  Controls,
  MiniMap,
  useNodesState,
  useEdgesState, 
  Position
} from "@xyflow/react"
import { AppNode, nodeTypes } from "@/components/workflow/nodes/type"
import { edgeTypes } from "@/components/workflow/edges/type"
import NodePropertiesPanel from "@/components/workflow/node-properties-panel"
import useWorkflowStore from "@/stores/workflow"
import type { Edge, OnConnect } from "@xyflow/react"

const initialNodes: AppNode[] = [
  {
    id: "start",
    type: "custom",
    position: { x: 0, y: 0 },
    sourcePosition: Position.Right,
    targetPosition: Position.Left,
    data: {
      title: "开始",
      type: "start",
      desc: ""
    },
    selected: false
  }
]
const initialEdges: Edge[] = []

/**
 * 工作室主页面
 */
const WorkflowPage = () => {
  const [nodes, setNodes, onNodesChange] = useNodesState(initialNodes)
  const [edges, setEdges, onEdgesChange] = useEdgesState(initialEdges)

  const isNodeToolbarVisible = useWorkflowStore((state) => state.isNodeToolbarVisible)
  const setIsNodeToolbarVisible = useWorkflowStore((state) => state.setIsNodeToolbarVisible)

  const onConnect: OnConnect = useCallback(
    (connection) => {
      // 这里使用自定义边缘
      const edge = { ...connection, type: "custom" }
      setEdges((edges) => addEdge(edge, edges))
    },
    [setEdges]
  )

  const handleGlobalClick = useCallback(() => {
    // 关闭节点选择器
    if (isNodeToolbarVisible) {
      setIsNodeToolbarVisible(false)
    }
  }, [isNodeToolbarVisible, setIsNodeToolbarVisible])

  return (
    <div className="w-full h-full" onClick={handleGlobalClick}>
      <ReactFlow
        nodes={nodes}
        edges={edges}
        nodeTypes={nodeTypes}
        edgeTypes={edgeTypes}
        minZoom={0.25}
        maxZoom={2}
        proOptions={{ hideAttribution: true }}
        onNodesChange={onNodesChange}
        onEdgesChange={onEdgesChange}
        onConnect={onConnect}
        fitView
      >
        <Background />
        <Controls />
        <MiniMap style={{ right: "410px" }} zoomable pannable />
        <NodePropertiesPanel />
      </ReactFlow>
    </div>
  )
}

export default WorkflowPage
